//
//  ViewController.swift
//  SmartPenSwift
//
//  Created by tql on 2021/2/3.
//

import UIKit
import SmartPenSDK
import SVProgressHUD



class ViewController: UIViewController {

   private var needShowOffList : Bool = true
   private var offlineDotArray : [Dot] = []
    private lazy var penCommAgent = PenCommAgent.getInstance()
    private var  lineColor : UIColor = UIColor.black
    private var  lineWidth : Int = 1
     lazy var lineWidthBtn : UIButton = {
        let btn : UIButton = self.makeButtonWith("线宽", "线宽-选中态", "线宽")// UIButton.init()
        
        return btn
    }()
    private lazy var lineColorBtn : UIButton = {
        let btn : UIButton = self.makeButtonWith("颜色", "icon_颜色_black", "颜色")// UIButton.init()
        
        return btn
    }()
    private lazy var clearBtn : UIButton = {
        let btn : UIButton = self.makeButtonWith("清除", "清除-选中态", "清除")//UIButton.init()
        
        return btn
    }()
    private lazy var replayBtn : UIButton = {
        let btn : UIButton = self.makeButtonWith("回放", "回放-选中态", "回放")//UIButton.init()
        
        return btn
    }()
    private lazy var moreBtn : UIButton = {
        let btn : UIButton = self.makeButtonWith("更多", "更多-选中态", "更多")//UIButton.init()
        
        return btn
    }()
    
    
    
    let OptionMoreVC = OptionMoreViewController()
    
    var popViews : [UIView]!
    lazy var lineWidthView : LineWidthToolsView = {
        let  view =  LineWidthToolsView()
        view.frame = CGRect(x: 0, y: kScreenHeight - 70 - kBottomSafeHeight - 70 - STATUSBAR_HEIGHT - 44, width: kScreenWidth, height: 70)
        view.currentWidth = lineWidth
        view.outBlock = {[weak self] width in
         print(width)
            self!.drawView.changeLineWidth(Float(width))
        }
        return view
    }()
    lazy var lineColorView : LineColorToolsView = {
       let view = LineColorToolsView()
        view.frame = CGRect(x: 0, y: kScreenHeight - 70 - kBottomSafeHeight - 70 - STATUSBAR_HEIGHT - 44, width: kScreenWidth, height: 70)
        view.outBlock = { [weak self] changeColor in
            print("cchangeColor\(changeColor)")
            self!.drawView.changeLineColor(changeColor)
            
        }
        return view
    }()
    lazy var replayView : ReplayToolsView = {
        
        let  frame : CGRect = CGRect(x: 0, y: kScreenHeight - 70 - kBottomSafeHeight - 70 - STATUSBAR_HEIGHT - 44, width: kScreenWidth, height: 70)
        let view : ReplayToolsView = ReplayToolsView.init(frame: frame)
        view.changeSpeedBlock = { [weak self] (changeLevel) in
            self?.drawView.rePlay(changeLevel)
        }
        view.PauseActionBlock = { [weak self] (pause) in
            self?.drawView.pauseReplay(pause)
            
        }
        
        return view
    }()
    
    
    
    lazy var drawView : DrawImageView  = {
        var topgap : CGFloat = 10
        var rect : CGRect = CGRect.init(x: 40, y: topgap, width: kScreenWidth - 80, height: kScreenHeight - 117 - 55)
        if IS_PAD {
            var height : CGFloat = kScreenHeight - 117 - 10
            var width : CGFloat = height * 1075 / 1512.0
            rect = CGRect(x: (kScreenWidth - width) / 2.0, y: topgap, width: width, height: height)
        }else if IS_IPHONEX(){
            var width  : CGFloat = kScreenHeight - 20
            var height : CGFloat = width / 1075 * 1512.0
            rect = CGRect(x: 10, y: 10 , width: width, height: height)
        }
        
        let view = DrawImageView.init(frame: rect)
        view._needStroke = true
        view.changeDrawViewWith(ifNeedStroke: true)
        
        return view
    }()
    
    lazy var offlineProgree  : OffLineProgressView = {
        
        let view : OffLineProgressView = OffLineProgressView()
        
        view.pauseDownloadBlock = {[weak self] (pauseOrGon) in
            self?.penCommAgent?.pauseOrContinue(toTransferOfflineData: pauseOrGon)
        }
        view.layer.cornerRadius = 5
        view.layer.shadowRadius = 5
        view.layer.shadowOffset = CGSize()
        view.layer.shadowOpacity = 0.2
        
        return view
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "SmartPen", style: .plain, target: self, action: #selector(optionToAbout))
        self.view.backgroundColor = .gray
        let bgImage  = UIImageView.init(frame: self.view.bounds)
        self.view.addSubview(bgImage)
        bgImage.image = UIImage.init(named: "LoginRegister")
        
        self.setupUI()
        self.setupToolBar()
        
        self.addChild(self.OptionMoreVC)
        self.popViews = [self.lineWidthView,self.lineColorView]
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifcate), name: NSNotification.Name(rawValue: "kNotification_AutoSaveLog"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notifcate), name: NSNotification.Name(rawValue: "kNotification_StrokePen"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notifcate), name: NSNotification.Name(rawValue: "kNotification_NeedFilter"), object: nil)
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        penCommAgent?.pensignal = self
//        penCommAgent?.onBlEScanListener = self
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self;

    }
    @objc func notifcate(_ notif : NSNotification ) -> Void{
        
    }
        
    func setupUI() -> Void {
        
        self.view.addSubview(self.drawView)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "连接智能笔", style: .plain, target: self, action: #selector(showDeviceList))
        
        
    }
    @objc func showDeviceList() -> Void {
        let vc = DeviceListTableViewController.init()
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func setupToolBar() -> Void {
        let bottomView = UIView.init(frame: CGRect.init(x: 0, y: self.view.frame.size.height - 70 - kBottomSafeHeight - STATUSBAR_HEIGHT - 44, width: self.view.frame.size.width, height: 70))
        self.view.addSubview(bottomView)
        bottomView.backgroundColor = UIColor.init(hex: "0xFFFDFD")
        
        let width : CGFloat = 50
        let gap : CGFloat = 20
        let btnHeight : CGFloat = 50
        var marginGap = (kScreenWidth - width * 5 - gap * 4) / 2.0
        
        bottomView.addSubview(self.lineWidthBtn)
        self.lineWidthBtn.frame = CGRect.init(x: marginGap, y: 10, width: width, height: btnHeight)
        
        marginGap += gap + width
        
        bottomView.addSubview(self.lineColorBtn)
        self.lineColorBtn.frame = CGRect.init(x: marginGap, y: 10, width: width, height: btnHeight)
        
        marginGap += gap + width
        
        bottomView.addSubview(self.clearBtn)
        self.clearBtn.frame = CGRect.init(x: marginGap, y: 10, width: width, height: btnHeight)
        
        marginGap += gap + width
        
        bottomView.addSubview(self.replayBtn)
        self.replayBtn.frame = CGRect.init(x: marginGap, y: 10, width: width, height: btnHeight)
        marginGap += gap + width
        
        bottomView.addSubview(self.moreBtn)
        self.moreBtn.frame = CGRect.init(x: marginGap, y: 10, width: width, height: btnHeight)
        
        
        
    }
   
    func hideMore() -> Void {
        self.moreBtn.isSelected = false
        self.hideAllPopViews()
    }

}
extension ViewController: TQLPenSignal{
    func onReceive(_ dot: Dot!) {
        debugPrint("onReceive == \(dot)")
        self.drawView.processEachDot(dot, false)
    }
    func onReceiveOfflineStrokes(_ dot: Dot!) {
        debugPrint(#function)

        self.drawView.processEachDot(dot, true)

    }
    func onFinishedOfflineDownload(_ isSuccess: Bool) {
        debugPrint(#function)
        
        if isSuccess {
            if self.offlineProgree.isDescendant(of: self.view) {
                self.offlineProgree.removeFromSuperview()
            }
            
            SVProgressHUD.showSuccess(withStatus: "离线数据下载成功")
            
            self.drawView.redrawCurrentData()
            
        }else{
            
        }

    }
    func onDeleteOfflineData(_ isSuccess: Bool) {
        debugPrint(#function)

    }
    
    
    
    func onOfflineDataList(_ offlineNotes: Int32) {
        debugPrint(#function)
        if needShowOffList == false {
            return
        }
        needShowOffList = false
        
        let alertController : UIAlertController = UIAlertController(title: "离线数据数量（Bytes）", message: "\(offlineNotes*10)", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
        

    }
    func onStartOfflineDownload(_ isSuccess: Bool) {
        debugPrint(#function)

    }
    func onStopOfflineDownload(_ isSuccess: Bool) {
        debugPrint(#function)

    }
    func offlineStrokesProgress(_ progress: Int32) {
        debugPrint(#function)
        
        if self.offlineProgree.isDescendant(of: self.view) == false {
            self.view.addSubview(self.offlineProgree)
            self.offlineProgree.snp.makeConstraints { (make) in
                make.height.equalTo(kScreenWidth * 160 / 375.0)
                make.width.equalTo(kScreenWidth * 180 / 375.0)
                make.centerX.equalTo(self.view)
                make.centerY.equalTo(self.view).offset(-60)
            }
            self.offlineProgree.hidepause = (self.penCommAgent?.getCurrentPenModel() == "YX-201" ) ? true : false
        }
        self.offlineProgree.progress = CGFloat(progress ) / 100.0
        
        
        
        
    }
    func onRecievePenElementCode(_ ElementCode: ElementCode!) {
        
    }
    func didUpdatecentralManagerState(_ state: Int32) {
        
    }
}



extension ViewController {
   
    func makeButtonWith(_ normalImage : String?, _ selectImage : String? , _ title : String?  ) -> UIButton {
        let width : CGFloat  = 50
        let btnHeight : CGFloat  = 50
        let btn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: width, height: btnHeight))

        if normalImage != nil {
            btn .setImage(UIImage.init(named: normalImage!), for: .normal)
        }
        
        
        if selectImage != nil {
            btn .setImage(UIImage.init(named: selectImage!), for: .selected)
        }
        
        if title != nil {
            btn.setTitle(title!, for: .normal)
        }
        
        btn.addTarget(self, action: #selector(btnClick(_ :)), for: .touchUpInside )
        return btn
    }
    @objc func btnClick(_ sender : UIButton){
        
        print("clkck:")
        self.unselectAllBtn(sender)
        self.hideAllPopViews()
        
        sender.isSelected = !sender.isSelected
        
        if sender.isSelected {
            
            if sender.isEqual(self.lineWidthBtn) {
                self.view.addSubview(self.lineWidthView)
            }
            if sender.isEqual(self.lineColorBtn) {
                self.view.addSubview(self.lineColorView)
            }
            if sender.isEqual(self.clearBtn) {
                self.clearDraw()
            }
            if sender.isEqual(self.replayBtn) {
                self.drawView.delegate = self
                self.view.addSubview(self.replayView)
                self.drawView.rePlay(1)
            }
            if sender.isEqual(self.moreBtn) {
                self.view.addSubview(self.OptionMoreVC.view)
                self.OptionMoreVC.delegateOM = self
                self.OptionMoreVC.delegateOD = self
                self.OptionMoreVC.view.frame = CGRect(x: kScreenWidth - 150 - 10,
                                                      y: kScreenHeight - 70 - kBottomSafeHeight - STATUSBAR_HEIGHT - 44 - 280 - 10,
                                                      width: 150,
                                                      height: 280)
                
            }
            
            
        }else{
            print("not dealed")
        }
        
    }
   
    func unselectAllBtn(_ btn : UIButton) -> Void {
        
        let btns = [self.lineWidthBtn,self.lineColorBtn,self.clearBtn,self.replayBtn,self.moreBtn]
        
        for bntins : UIButton in btns {
            if btn .isEqual(bntins) {
                continue
            }else{
                bntins.isSelected = false
            }
        }
        
    }
    
    func hideAllPopViews() -> Void {
        if self.lineWidthView.isDescendant(of: self.view) {
            self.lineWidthView.removeFromSuperview()
        }
        if self.lineColorView.isDescendant(of: self.view) {
            self.lineColorView.removeFromSuperview()
        }
        
        if self.replayView.isDescendant(of: self.view) {
            self.replayView.removeFromSuperview()
        }
        
        if self.offlineProgree.isDescendant(of: self.view) {
            self.offlineProgree.removeFromSuperview()
        }
        if self.OptionMoreVC.view.isDescendant(of: self.view) {
            self.OptionMoreVC.view.removeFromSuperview()
        }
    }
    func clearDraw() -> Void {
        
    }
    
    @objc func AlertToConnectPen(){
        let alert : UIAlertController = UIAlertController.init(title: "智能笔", message: "请先连接智能笔...", preferredStyle: .alert)
        let connectAction : UIAlertAction = UIAlertAction.init(title: "去连接", style: .default) {[weak self] (action) in
            self?.showDeviceList()
        }
        connectAction.setValue(UIColor(hex: "FF4E4E"), forKey: "_titleTextColor")
        alert.addAction(connectAction)
        
        let cancelAction : UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        cancelAction.setValue(UIColor(hex: "8492A6"), forKey: "_titleTextColor")
        
        alert.addAction(cancelAction)
        alert.popoverPresentationController?.sourceView = self.view
        alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 10, height: 10)
        
        
        self.present(alert, animated: true, completion: nil)
    }
    
}

extension ViewController : ReplayDelegate{
    func StopReplayBeacuseNoData() {
        debugPrint(#function)
    }
    
    func ReplayProgress(_ currentIndex: Int, _ total: Int) {
        debugPrint(#function)
    }
    
    func replayEnd() {
        debugPrint(#function)
    }
    
    
    
}
extension ViewController : OptionMoreDelegate{
    
    func optionToOTA() {
        debugPrint("optionToOTA")
        if ( penCommAgent?.interface.findConnectedPeripherals()!.count)! > 0 {

            
            
        }else{
            AlertToConnectPen()
        }
    }
    func optionToGetRecognize() {
        debugPrint("optionToGetRecognize")

    }
   @objc func optionToAbout() {
        debugPrint("optionToAbout")
        let vc : AboutUsViewController = AboutUsViewController.init()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func optionToChooseTXT() {
        debugPrint("optionToChooseTXT")

    }
    func optionToGetPenInfo() {
        debugPrint("optionToGetPenInfo")
        
        if ( penCommAgent?.interface.findConnectedPeripherals()!.count)! > 0 {
            let vc : PenInfoViewController = PenInfoViewController.init()
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else{
            AlertToConnectPen()
//            let vc : PenInfoViewController = PenInfoViewController.init()
//            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        self.moreBtn.isSelected = false
        self.hideAllPopViews()
        

    }
    
}
extension ViewController : OffLineDelegate {
    
    func ODToGetAllOfflineData() {
        debugPrint("ODToGetAllOfflineData")
        if ( penCommAgent?.interface.findConnectedPeripherals()!.count)! > 0 {
            
            self.penCommAgent?.transferOfflineData(true)
        }else{
            self.AlertToConnectPen()
        }
        self.hideMore()
    }
    func ODToGetAllOfflineDataCount() {
        debugPrint("ODToGetAllOfflineDataCount")
        needShowOffList = true
        if ( penCommAgent?.interface.findConnectedPeripherals()!.count)! > 0 {
//        if penCommAgent?.interface.findConnectedPeripherals()!.count > 0 {
            self.penCommAgent?.reqOfflineDataInfo()
        }else{
            self.AlertToConnectPen()
        }
    
        self.hideMore()

    }
    func ODToStopGetAllOfflineData() {
        debugPrint("ODToStopGetAllOfflineData")

        self.penCommAgent?.transferOfflineData(false)
    }
    func ODToClearAllOfflineData() {
        debugPrint("ODToClearAllOfflineData")
        print(#function)
        self.penCommAgent?.deleteOfflineData()
    }
}

extension ViewController : UIGestureRecognizerDelegate{
    
}
